package vincent.com.layouttest.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * Created by chenzhengwen on 2015/12/7.
 */
public class DrawDrawableView extends ImageView {

    public DrawDrawableView(Context context) {
        this(context, null);
    }

    public DrawDrawableView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DrawDrawableView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        ColorDrawable colorDrawable = new ColorDrawable(Color.BLUE);
        colorDrawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
        colorDrawable.draw(canvas);

        Bitmap bitmap = Bitmap.createBitmap(getMeasuredWidth()/2, getMeasuredHeight()/2, Bitmap.Config.ARGB_8888);
        Canvas bitmapCanvas = new Canvas(bitmap);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        bitmapCanvas.drawCircle(getMeasuredWidth() / 4, getMeasuredHeight() / 4, getMeasuredWidth() / 4, paint);

        int count = canvas.save();

        BitmapDrawable bitmapDrawable = new BitmapDrawable(getContext().getResources(), bitmap);
        bitmapDrawable.setBounds(0, 0, getMeasuredWidth() / 2, getMeasuredHeight() / 2);
        canvas.translate(getMeasuredWidth() / 4, getMeasuredHeight() / 4);
        bitmapDrawable.draw(canvas);

        canvas.restoreToCount(count);
//        paint.setColor(Color.BLACK);
//        Rect bitmapRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
//        canvas.drawBitmap(bitmap, null, bitmapRect, paint);
        canvas.drawBitmap(bitmap, getMeasuredWidth()/2, getMeasuredHeight()/2, paint);
    }
}
